class DSU:
    def __init__(self, N):
        self.parent = [i for i in range(N)]

    def find(self, node):
        if self.parent[node] != node:
            self.parent[node] = self.find(self.parent[node])

        return self.parent[node]

    def union(self, x, y):
        px = self.find(x)
        py = self.find(y)

        self.parent[py] = px


class Solution:
    def removeStones(self, stones: list) -> int:
        dsu = DSU(20000)
        for x, y in stones:
            dsu.union(x, 10000 + y)

        parent = set()
        for x, _ in stones:
            parent.add(dsu.find(x))

        return len(stones) - len(parent)
